import express from 'express'
import { queryAnimationPagination } from './db'
import ejs from 'ejs'
import moment from 'moment'
const app = express()
import qs from 'querystring'
app.set('view engine', 'ejs');

const dateFormat = function (obj: Date | string, format?: string) {
  if (format == undefined) {
    format = 'YYYY-MM-DD';
  }
  var ret = moment(obj).format(format);
  return ret == 'Invalid date' ? '0000-00-00' : ret;
}

const parseUInt = function (str: string, def: number) {
  const num = parseInt(str)
  if (num > 0) {
    return num
  }
  return def
}

type Query = {
  author: string
};

app.get('/', function (req, res) {
  let { page, limit, author } = req.query
  page = parseUInt(page, 1)
  limit = parseUInt(limit, 10)

  let query: Partial<Query> = {}

  if (author) {
    query.author = author
  }

  const pagination = {
    prev: page > 1 ? qs.stringify({
      ...query,
      page: page - 1,
      limit
    }) : '#',
    next: qs.stringify({
      ...query,
      page: page + 1,
      limit
    }),
  }

  queryAnimationPagination(query, page, limit).then(({ results }) => {
    res.render('index', { animations: results, dateFormat, pagination });
  }).catch(e => console.error(e))
});

app.listen(3000, 'localhost', () => console.log('Example app listening on port 3000!'))